﻿@page "/"
@using System.Text
@using System.Text.Json
@inject HttpClient Http
@inject IJSRuntime JS

<PageTitle>Northwind&trade; Smart Sales Assistant</PageTitle>

<div class="chat-container">
    <div class="chat-header">
        <Title Level="5">
            <Icon Type="robot" Theme=@IconThemeType.Outline />
            Northwind&trade; Smart Sales Assistant
        </Title>
    </div>
    
    <div class="chat-messages" @ref="_messagesContainer">
        @if (_messages.Count == 0)
        {
            <div class="welcome-message">
                <Icon Type="robot" Theme=@IconThemeType.Outline Style="font-size: 48px; color: #1890ff;" />
                <Text Type="@TextElementType.Secondary" Style="font-size: 18px;">
                    Hello! I'm your AI assistant for Northwind Sales. How can I help you today?
                </Text>
            </div>
        }
        else
        {
            @foreach (var message in _messages)
            {
                <div class="message @(message.IsUser ? "user-message" : "assistant-message")">
                    <div class="message-avatar">
                        @if (message.IsUser)
                        {
                            <Avatar Icon="user" />
                        }
                        else
                        {
                            <Avatar Icon="robot" Style="background-color: #1890ff;" />
                        }
                    </div>
                    <div class="message-content">
                        <div class="message-text">
                            @((MarkupString)message.Content)
                        </div>
                        <div class="message-time">
                            <Text Type="@TextElementType.Secondary" Style="font-size: 12px;">
                                @message.Timestamp.ToString("HH:mm")
                            </Text>
                        </div>
                    </div>
                </div>
            }
        }
        
        @if (_isLoading)
        {
            <div class="message assistant-message">
                <div class="message-avatar">
                    <Avatar Icon="robot" Style="background-color: lightgray;" />
                </div>
                <div class="message-content">
                    <div class="typing-indicator">
                        <Spin Size=@SpinSize.Small />
                        <Text Type="@TextElementType.Secondary" Style="margin-left: 8px;">
                            Thinking & typing...
                        </Text>
                    </div>
                </div>
            </div>
        }
    </div>
    
    <div class="chat-input">
        <div class="chat-input-row">
            <Input @bind-Value="_currentMessage"
                   @ref="_inputElement"
                   OnInput="OnInputChange"
                   OnPressEnter="SendMessage"
                   Placeholder="Ask me anything about Northwind products, orders, or customers..."
                   Disabled="@_isLoading"
                   Style="flex: 1; margin-right: 8px;" />
            <Button Type="@ButtonType.Primary" 
                    Icon="send" 
                    OnClick="SendMessage"
                    Loading="@_isLoading"
                    Disabled="@(_isLoading || string.IsNullOrWhiteSpace(_currentMessage))">
                Send
            </Button>
        </div>
    </div>
</div>

@code {
    private readonly List<ChatMessage> _messages = [];
    private string _currentMessage = string.Empty;
    private bool _isLoading;
    private ElementReference _messagesContainer;
    private Input<string>? _inputElement;
    
    public class ChatMessage
    {
        public string Content { get; set; } = "";
        public bool IsUser { get; set; }
        public DateTime Timestamp { get; set; } = DateTime.Now;
    }

    private void OnInputChange(ChangeEventArgs e)
    {
        _currentMessage = e.Value?.ToString() ?? "";
        StateHasChanged();
    }
    
    private async Task SendMessage()
    {
        if (string.IsNullOrWhiteSpace(_currentMessage) || _isLoading)
            return;
            
        var userMessage = _currentMessage.Trim();
        _currentMessage = "";
        StateHasChanged();
        
        // Add user message
        _messages.Add(new ChatMessage
        { 
            Content = userMessage, 
            IsUser = true 
        });

        // Add assistant message placeholder for streaming
        var assistantMessage = new ChatMessage
        {
            Content = "",
            IsUser = false
        };
        _messages.Add(assistantMessage);
        
        _isLoading = true;
        StateHasChanged();
        await ScrollToBottom();
        
        try
        {
            // Call the API
            var request = new HttpRequestMessage(HttpMethod.Post, "api/search")
            {
                Content = new StringContent(
                    JsonSerializer.Serialize(new { query = userMessage }),
                    Encoding.UTF8,
                    "application/json")
            };
                
            using var response = await Http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            
            if (response.IsSuccessStatusCode)
            {
                await using var stream = await response.Content.ReadAsStreamAsync();
                using var reader = new StreamReader(stream);

                var buffer = new char[16];
                int read;
                while ((read = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    var chunk = new string(buffer, 0, read);
                    assistantMessage.Content += chunk;
                    StateHasChanged();
                    await ScrollToBottom();
                    await Task.Delay(15);
                }
            }
            else
            {
                assistantMessage.Content = "I apologize, but I'm having trouble processing your request right now. Please try again later.";
            }
        }
        catch (Exception ex)
        {
            assistantMessage.Content = $"An error occurred: {ex.Message}";
        }
        finally
        {
            
            _isLoading = false;
            StateHasChanged();
            await ScrollToBottom();
            _inputElement?.Focus();
        }
    }
    
    private async Task ScrollToBottom()
    {
        await Task.Delay(50); // Small delay to ensure DOM is updated
        await JS.InvokeVoidAsync("scrollToBottom", _messagesContainer);
    }

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            _inputElement?.Focus();
        }
        return base.OnAfterRenderAsync(firstRender);
    }

}

<style>
    .chat-container {
        height: 80vh;
        display: flex;
        flex-direction: column;
        max-width: 800px;
        margin: 0 auto;
        border: 1px solid #d9d9d9;
        border-radius: 8px;
        overflow: hidden;
    }
    
    .chat-header {
        padding: 12px;
        border-bottom: 1px solid #d9d9d9;
        background-color: #fafafa;
    }

    .chat-input-row {
        display: flex;
        flex-direction: row;
        align-items: center;
        gap: 0;
    }
    
    .chat-messages {
        flex: 1;
        overflow-y: auto;
        padding: 16px;
        display: flex;
        flex-direction: column;
        gap: 16px;
    }
    
    .welcome-message {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12px;
        margin-top: 50px;
        text-align: center;
    }
    
    .message {
        display: flex;
        gap: 12px;
        max-width: 80%;
    }
    
    .user-message {
        align-self: flex-end;
        flex-direction: row-reverse;
    }
    
    .assistant-message {
        align-self: flex-start;
    }
    
    .message-avatar {
        flex-shrink: 0;
    }
    
    .message-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 4px;
    }
    
    .message-text {
        background-color: #FFD66B;
        padding: 12px;
        border-radius: 8px;
        white-space: pre-wrap;
        word-wrap: break-word;
    }
    
    .user-message .message-text {
        background-color: #4DA8DA;
        color: white;
    }
    
    .message-time {
        font-size: 12px;
        opacity: 0.7;
    }
    
    .user-message .message-time {
        text-align: right;
    }
    
    .chat-input {
        padding: 16px;
        border-top: 1px solid #d9d9d9;
        background-color: #fafafa;
    }
    
    .typing-indicator {
        display: flex;
        align-items: center;
        padding: 12px;
        background-color: #f5f5f5;
        border-radius: 8px;
    }
    
    .chat-messages::-webkit-scrollbar {
        width: 6px;
    }
    
    .chat-messages::-webkit-scrollbar-track {
        background: #f1f1f1;
    }
    
    .chat-messages::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;
    }
    
    .chat-messages::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }
</style>

<script>
    window.scrollToBottom = (element) => {
        if (element) {
            element.scrollTop = element.scrollHeight;
        }
    };
</script>
